<!DOCTYPE html>
<html lang="zh-CN">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>访问文件夹</title>
  <style>
    *,
    *::after,
    *::before {
      margin: 0;
      padding: 0;
      box-sizing: border-box;
    }

    :root {
      min-height: 100vh;
    }

    :root:focus-within {
      scroll-behavior: smooth;
    }

    body {
      min-height: inherit;
    }
  </style>
</head>

<body>
  <button>打开文件夹</button>
</body>
<script>
  "use strict"; {
    let btn = document.querySelector("button");
    btn.addEventListener("click", async () => {
      try {
        // 获取文件夹的句柄
        let handle = await showDirectoryPicker();
        let res = await processHandle(handle);

        // 获取文件
        let file = await res.children[1].getFile();

        // 读取文件内容
        await getFileContext(file);

        // 高亮显示代码，使用第三方库 highlight.js
      } catch (err) {
        console.error(`用户点击取消按钮后，触发的效果`, err);
      };
    });

    // 处理文件句柄
    async function processHandle(handle) {
      // 判断文件类型，如果文件为 file 类型，则不做任何递归处理了
      if (handle.kind === "file") {
        return handle;
      };

      handle.children = [];

      // handle 异步迭代器
      let iter = await handle.entries();

      // 遍历异步迭代器
      for await (let item of iter) {
        // 递归文件夹中的内容
        let res = await processHandle(item[1]);
        handle.children.push(res);
      };

      return handle;
    };

    // 获取文件内容
    async function getFileContext(file) {
      const reader = new FileReader();

      reader.addEventListener("load", e => {
        let res = e.target.result;
        console.log(res);
        return res;
      });

      // 将文件读取处理，读取的格式是 utf-8
      reader.readAsText(file, "utf-8");
    };
  };
</script>

</html>